/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.messaging

import org.bson.BSON
import org.ibiblio.terasaur.messaging.webqueue.Command

class WebQueueService {
    static transactional = true
    static rabbitQueue = 'terasaur.web'

    void handleMessage(String textMessage) {
        log.error("Received message in WebQueueService::handleMessage(String)")
    }

    void handleMessage(Map mapMessage) {
        log.error("Received message in WebQueueService::handleMessage(Map)")
    }

    void handleMessage(byte[] byteMessage) {
        //log.info("Received message in WebQueueService::handleMessage(byte[])")
        try {
            def message = _decodeMessage(byteMessage)
            Command c = Command.create(message)
            Map result = c.run()
        } catch (Exception e) {
            log.error("Error handling message: " + e.message)
        }
    }

    protected Map _decodeMessage(byte[] byteMessage) {
        def bson = new BSON()
        def decode = bson.decode(byteMessage)
        Map m = decode.toMap()
        return m
    }
}
